package com.ruiao.car.config;


import com.ruiao.car.dto.ResultDto;
import com.ruiao.car.enums.ResultEnum;
import com.ruiao.car.utils.IllegalRequestException;
import com.ruiao.car.utils.UnLoginException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import java.util.List;

/**
 * 全局异常处理器
 *
 * @author Vincent.Pei
 * @date 2019/3/8上午10:39
 * @Description:
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    @ResponseBody
    @ExceptionHandler(Exception.class)
    public Object handleException(Exception e) {

        if (e instanceof UnLoginException) {
            return new ResultDto(ResultEnum.NO_LOGIN);
        } else if (e instanceof IllegalRequestException) {
            return new ResultDto(ResultEnum.ILLEGAL_REQUEST);
        } else if (e instanceof MaxUploadSizeExceededException) {
            return new ResultDto(ResultEnum.IMG_TOO_BIG);
        } else if (e instanceof MethodArgumentNotValidException) {
            BindingResult bindingResult = ((MethodArgumentNotValidException) e).getBindingResult();
            if (bindingResult.hasErrors()) {
                List<FieldError> errorList = bindingResult.getFieldErrors();
                String errorMsg = errorList.get(0).getDefaultMessage();
                return new ResultDto(ResultEnum.ILLEGAL_PARAM.MsgRebuild(errorMsg));
            }

        } else if (e instanceof BusinessException) {
            BusinessException businessException = (BusinessException) e;
            return new ResultDto(businessException.getResultEnum());
        } else {
            if (ResultEnum.TOO_MANY_REQUEST.name().equals(e.getMessage())) {
                return new ResultDto(ResultEnum.TOO_MANY_REQUEST);
            }
        }
        log.error(ExceptionUtils.getFullStackTrace(e));
        return new ResultDto(ResultEnum.SYSTEM_ERROR);

    }
}

